package org.javanile.sms.demo;

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import org.javanile.sms.Server;

/**
 * An example MIDlet to send text via an SMS MessageConnection
 */
public class MIDletDemo3 extends MIDlet implements CommandListener {

    /**
     * Object to manage SMS sending and receiving
     */
    Server      sms;

    /** user interface command */
    Display     display;
    Form        form;
    TextField   number;
    TextField   message;
    Command     exitCommand = new Command("Exit", Command.EXIT, 2);
    Command     okCommand = new Command("OK", Command.OK, 1);

    public MIDletDemo3() {

        /**
         * Initialize SMS server
         */
        sms = new Server(this);

        display = Display.getDisplay(this);
        number	= new TextField("Number", null, 32, TextField.ANY);
        message = new TextField("Message", null, 32, TextField.ANY);

        form = new Form("Demo 1");
        form.append(number);
        form.append(message);
	form.addCommand(exitCommand);
	form.addCommand(okCommand);
        form.setCommandListener(this);
    }

    /**
     * startApp should return immediately to keep the dispatcher
     * from hanging.
     */
    public void startApp() {
        sms.start();
	sms.receive(new Server.Incoming() {
            public void received(String msg) {
                form.append(msg);
            }
	});

      	display.setCurrent(form);
    }

    /**
     * Remember what screen is showing
     */
    public void pauseApp() {        
    }

    /**
     * Destroy must cleanup everything.
     * @param unconditional true if a forced shutdown was requested
     */
    public void destroyApp(boolean unconditional) {
	sms.stop();
    }

    /**
     * Respond to commands, including exit
     * @param c user interface command requested
     * @param s screen object initiating the request
     */
    public void commandAction(Command c, Displayable s) {
        try {
            if (c == okCommand) {
                String address = number.getString();
                String text = message.getString();
                sms.send(address,text);

            } else if ((c == exitCommand) || (c == Alert.DISMISS_COMMAND)) {
                destroyApp(false);
                notifyDestroyed();

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }    
}
